package com.gxl.common;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 能进入servletDispatcher的就可以被拦截
 * @author set_free
 *
 */
public class MyInterceptor implements HandlerInterceptor{
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		System.out.println("MyInterceptor.preHandle()");
		HandlerMethod hm = (HandlerMethod)handler;
		Method method = hm.getMethod();
		String mname = method.getName();
		System.out.println("拦截的是："+mname);
		return true;//是否放行
		
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("MyInterceptor.postHandle()");
		if(null != modelAndView){
		Map<String,Object> map = modelAndView.getModel();
			for(String key:map.keySet()){
				if(map.get(key) instanceof String){
					map.put(key, map.get(key).toString().replaceAll("中国", "**"));
				}
			}
		}
		String viewName = modelAndView.getViewName();
		System.out.println("跳转的路径："+viewName);
	}
	//恒执行方法，不管异不异常都会执行，一般可以用在日志记录上
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("MyInterceptor.afterCompletion()");
		if(ex != null){
			Logger logger = Logger.getLogger(MyInterceptor.class);
			//存入日志
			System.out.println("出现的异常是："+ex);
		}
		
	}

}
